//
//  successDemo.m
//  AoJi
//
//  Created by chen on 15/2/12.
//  Copyright (c) 2015年 xuanheng. All rights reserved.
//

#import <Foundation/Foundation.h>

#import "goldenViewer.h"
#import "PPiFlatSegmentedControl.h"
#import "MJRefresh.h"
#import "AppDelegate.h"
#import "DetailWebViewController.h"
#import "DataSingleTon.h"
#import "GoldenviewerTableViewCell.h"
@implementation goldenViewer
-(id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if(self){
        goldenIndex= 1;
        [self gotcitylist];
        successArray = [NSMutableArray array];
        viewerTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320,frame.size.height) style:UITableViewStylePlain];
        viewerTableView.delegate = self;
        viewerTableView.dataSource = self;
        viewerTableView.separatorStyle=UITableViewCellSeparatorStyleNone;
        [viewerTableView registerClass:[GoldenviewerTableViewCell class] forCellReuseIdentifier:@"cell"];
        [self addSubview:viewerTableView];
        [viewerTableView addFooterWithCallback:^{
            NSLog(@"加载更多。。。");
           
        }];
        [self runsuccessdemo];
        
    }
    return self;
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [successArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    GoldenviewerTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
   
    
    NSMutableDictionary *tempDic = [[NSMutableDictionary alloc] initWithDictionary:[successArray objectAtIndex:indexPath.row]];
    cell.paramdic=tempDic;
    
        [ cell.yuYueBtn addTarget:self action:@selector(yuyueFun:) forControlEvents:UIControlEventTouchUpInside];
        NSLog(@"%ld",(long)indexPath.row);
         cell.yuYueBtn.tag = indexPath.row;
    
    
    return cell;
}

-(void)yuyueFun:(id)sender{
    [self useTapGestureRecognizerclose];
    UIButton* temBtn = (UIButton*)sender;
    NSInteger tagIndex = temBtn.tag;
    [self showyuYueViewFun:tagIndex];
}

-(void)showyuYueViewFun:(NSInteger)teacherID{
    UIImageView* yuYueView = [[UIImageView alloc] initWithFrame:CGRectMake(15, -10, 597/2, 446/2+60)];
    yuYueView.tag = 998;
    [yuYueView setImage:[UIImage imageNamed:@"tankuang-bj.png"]];
    yuYueView.userInteractionEnabled = true;
    [self addSubview:yuYueView];
    
    //分割线
    for (int i=1; i<6; i++) {
        UIImageView* fenGeLine = [[UIImageView alloc] initWithFrame:CGRectMake(18, i*45.9+5, 260, 1)];
        [fenGeLine setImage:[UIImage imageNamed:@"fengjiexian.png"]];
        [yuYueView addSubview:fenGeLine];
        
        UILabel* nameTitle = [[UILabel alloc] initWithFrame:CGRectMake(50, (i-1)*45+20, 100, 20)];
        if (i == 1) {
            nameTitle.text = @"姓       名:";
        }
        else if(i == 2){
            nameTitle.text = @"所在城市:";
        }
        else if(i == 3){
            nameTitle.text = @"电话号码:";
        }
        else if(i == 4){
            nameTitle.text = @"邮       箱:";
        }
        else if (i == 5){
            nameTitle.text = @"出国意向:";
        }
        nameTitle.textColor = [self getCorlor:@"B2B1B1"];
        [yuYueView addSubview:nameTitle];
        
    
        
        UIImageView* imgPic = [[UIImageView alloc] initWithFrame:CGRectMake(20, (i-1)*45.5+18, 22, 22)];
        if (i == 1) {
            [imgPic setImage:[UIImage imageNamed:@"xingmin.png"]];
        }
        else if(i == 2){
            [imgPic setImage:[UIImage imageNamed:@"shuozaichengshi.png"]];
        }
        else if(i == 3){
            [imgPic setImage:[UIImage imageNamed:@"lianxidianhuayuaquan.png"]];
        }
        else if(i == 4){
            [imgPic setImage:[UIImage imageNamed:@"mail.png"]];
        }
        else if (i == 5){
            [imgPic setImage:[UIImage imageNamed:@"liuxue-yixiang.png"]];
        }
        [yuYueView addSubview:imgPic];
    }
    
    nameTextView = [[UITextField alloc] initWithFrame:CGRectMake(130, 17, 155, 25)];
    cityTextView = [[UITextField alloc] initWithFrame:CGRectMake(130, 1*45.5+17, 155, 25)];
    phoneTextView = [[UITextField alloc] initWithFrame:CGRectMake(130, 2*45.5+17, 155, 25)];
    emailTextView = [[UITextField alloc] initWithFrame:CGRectMake(130, 3*45.5+17, 155, 25)];
    boardTextView = [[UITextField alloc] initWithFrame:CGRectMake(130, 4*45.5+17, 155, 25)];
    
    
    nameTextView.tag = 10;
    nameTextView.placeholder = @"请输入姓名";
    cityTextView.placeholder = @"请输入所在城市";
    phoneTextView.placeholder = @"请输入您的电话号码";
    emailTextView.placeholder = @"请输入邮箱地址";
    boardTextView.placeholder = @"请输入出国意向";
    nameTextView.delegate = self;
    nameTextView.returnKeyType = UIReturnKeyDone;
    nameTextView.keyboardType = UIKeyboardTypeDefault;
    nameTextView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    [yuYueView addSubview:nameTextView];
    
    cityTextView.delegate = self;
    cityTextView.returnKeyType = UIReturnKeyDone;
    cityTextView.keyboardType = UIKeyboardTypeDefault;
    cityTextView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    [yuYueView addSubview:cityTextView];
    
    phoneTextView.delegate = self;
    phoneTextView.returnKeyType = UIReturnKeyDone;
    phoneTextView.keyboardType = UIKeyboardTypeDefault;
    phoneTextView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    [yuYueView addSubview:phoneTextView];
    
    emailTextView.delegate = self;
    emailTextView.returnKeyType = UIReturnKeyDone;
    emailTextView.keyboardType = UIKeyboardTypeDefault;
    emailTextView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    [yuYueView addSubview:emailTextView];
    
    boardTextView.delegate = self;
    boardTextView.returnKeyType = UIReturnKeyDone;
    boardTextView.keyboardType = UIKeyboardTypeDefault;
    boardTextView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    [yuYueView addSubview:boardTextView];
    
    UIButton* yueyueOK = [[UIButton alloc] initWithFrame:CGRectMake(7, 235, 568/2, 81/2)];
    [yueyueOK addTarget:self action:@selector(yuyueconfirm:) forControlEvents:
     UIControlEventTouchUpInside];
    [yueyueOK setBackgroundImage:[UIImage imageNamed:@"but.png"] forState:UIControlStateNormal];
    [yueyueOK setTitle:@"提交预约" forState:UIControlStateNormal];
    yueyueOK.tag = teacherID;
    
    [yuYueView addSubview:yueyueOK];

}

-(void)yuyueconfirm:(id)sender{
    
    NSMutableDictionary* dicSave = [[NSMutableDictionary alloc] init];
    UIButton* tempBtn = (UIButton*)sender;
    NSInteger temINDEX =tempBtn.tag;
    NSString* teacherID = [[successArray objectAtIndex:temINDEX] objectForKey:@"id"];
    [dicSave setObject:nameTextView.text forKey:@"AF_Name"];
    [dicSave setObject:phoneTextView.text forKey:@"AF_Tel"];
    [dicSave setObject:emailTextView.text forKey:@"AF_Email"];
    [dicSave setObject:cityTextView.text forKey:@"AF_City"];
    [dicSave setObject:boardTextView.text forKey:@"AF_Country"];
    UIView* tempview = (UIView*)[self viewWithTag:998];
    if ([self checkInformationIllegal]){
        [tempview removeFromSuperview];
        [YHNetwork getInformationWithReguestType:RequestTypePost WithParameters:dicSave WithApi:[NSString stringWithFormat:@"study/activity/enter?id=%@",teacherID]  WhenSuccess:^(NSMutableDictionary *response) {
           
            NSMutableArray *temearr=response;
            
            NSDictionary *dicJson = [NSDictionary dictionaryWithDictionary:response];
            NSString *str_message = [dicJson objectForKey:@"message"];
            NSString *code = @"";
            if (![[dicJson objectForKey:@"code"] isKindOfClass:[NSString class]])
            {
                code = [NSString stringWithFormat:@"%@",[dicJson objectForKey:@"code"]];
            } else
            {
                code = [dicJson objectForKey:@"code"];
            }
            
            if ([code isEqualToString:@"1"])
            {
                [self noticeError:str_message];
            } else
            {
                [self noticeError:@"报名成功"];
            }
        } WhenFailure:^(NSError *failure) {
        }];
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
        return 92;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSString* webViewUrl = [NSString stringWithFormat:@"%@train/teacher/detail?id=%@",baseUrl,[[successArray objectAtIndex:indexPath.row] objectForKey:@"id"]];
    
    DetailWebViewController *webVc=[[DetailWebViewController alloc]init];
    
    NSString *str=webViewUrl;
    webVc.urlString=str;
    [[self viewController].navigationController pushViewController:webVc animated:YES];
    

}

- (UIViewController *)viewController {
    for (UIView* next = [self superview]; next; next = next.superview) {
        UIResponder *nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)nextResponder;
        }
    }
    return nil;
}

-(void)runsuccessdemo{
    NSMutableDictionary* dicSave = [[NSMutableDictionary alloc] init];
    NSInteger goldenCout = [successArray count];
    NSString* lastID = nil;
    if (goldenCout!=0) {
      lastID =[[successArray lastObject] objectForKey:@"id"];
    }
    else{
        lastID = @"";
    }
    [dicSave setObject:[DataSingleTon shareDataSingleTon].catdir forKey:@"ccode"];
    [dicSave setObject:@"10" forKey:@"cityid"];
    [dicSave setObject:lastID forKey:@"lastid"];
    [YHNetwork getInformationWithReguestType:RequestTypeGet WithParameters:dicSave WithApi:@"study/adviser" WhenSuccess:^(NSMutableDictionary *response) {
        for (id dic in response) {
            [successArray addObject:dic];
        }
        [viewerTableView reloadData];
        goldenIndex++;
        [viewerTableView footerEndRefreshing];

    } WhenFailure:^(NSError *failure) {
        
    }];
}


-(void)gotcitylist{
    NSMutableDictionary* dicSave = [[NSMutableDictionary alloc] init];
    [YHNetwork getInformationWithReguestType:RequestTypeGet WithParameters:dicSave WithApi:@"city" WhenSuccess:^(NSMutableDictionary *response) {
        for (id dic in response) {
            [cityList addObject:dic];
        }
    } WhenFailure:^(NSError *failure) {
        
    }];
}



-(void)useTapGestureRecognizerclose {
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handletapPressGesture:)];
    AppDelegate *app = [[UIApplication sharedApplication] delegate];
    [app.window addGestureRecognizer:tapGesture];

}
//
-(void)handletapPressGesture:(UITapGestureRecognizer*)sender{
    CGPoint point = [sender locationInView:self];
    UIView* babalView = (UIView*)[self viewWithTag:998];
    if (point.y<babalView.frame.origin.y || point.y >babalView.frame.origin.y+babalView.frame.size.height||point.x<babalView.frame.origin.x||point.x>babalView.frame.origin.x+babalView.frame.size.width) {
                                     //一定要移除手势 否则下次 没有子视图的时候 点击 会崩溃拉
                                     [babalView removeFromSuperview];
        AppDelegate *app = [[UIApplication sharedApplication] delegate];
        [app.window removeGestureRecognizer:sender];
    }
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch=[[event allTouches] anyObject];
    if (touch.tapCount >=1) {
        [phoneTextView resignFirstResponder];
        [nameTextView resignFirstResponder];
        [cityTextView resignFirstResponder];
        [emailTextView resignFirstResponder];
        [boardTextView resignFirstResponder];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

-(void)viewDidDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)keyboardWillShow:(NSNotification *)aNotification
{
    CGRect keyboardRect = [[[aNotification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] CGRectValue];
    NSTimeInterval animationDuration = [[[aNotification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    CGRect frame = self.frame;
    frame.size.height -= keyboardRect.size.height;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    self.frame = frame;
    [UIView commitAnimations];
}

- (void)keyboardWillHide:(NSNotification *)aNotification
{
    CGRect keyboardRect = [[[aNotification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] CGRectValue];
    NSTimeInterval animationDuration = [[[aNotification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    CGRect frame = self.frame;
    frame.size.height += keyboardRect.size.height;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    self.frame = frame;
    [UIView commitAnimations];
}


-(void)textFieldDidBeginEditing:(UITextField *)textField{

}

//当开始点击textField会调用的方法


//当textField编辑结束时调用的方法



//按下Done按钮的调用方法，我们让键盘消失

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    
    return YES;
    
}


//检验名字是否合法
-(BOOL) validateName:(NSString *)Name
{
    if (nameTextView.text.length == 0)
    {
        return NO;
    } else
    {
        for(int i=0; i< [Name length];i++)
        {
            int a = [Name characterAtIndex:i];
            if( !(a > 0x4e00 && a < 0x9fff))
                //不是汉字
                return NO;
        }
    }
    
    return YES;
}


//判断是否是数字
- (BOOL)isPureNumandCharacters:(NSString *)string
{
    if (phoneTextView.text.length != 11)
    {
        return NO;
    }
    else
    {
        string = [string stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];
        if(string.length > 0)
        {
            return NO;
        }
    }
    
    return YES;
}

//检验邮箱是否合法
-(BOOL) validateEmail:(NSString *)email
{
    
    if(emailTextView.text.length == 0)
    {
        return NO;
    }
    else
    {
        NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
        NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
        return [emailTest evaluateWithObject:email];
    }
}
//检测要上传的信息是否合法
-(BOOL)checkInformationIllegal
{
    if (![self validateName:nameTextView.text])
    {
        [self noticeError:@"您输入的名字必须为中文"];
        return  NO;
    }
    
    if (cityTextView.text.length == 0)
    {
        [self noticeError:@"请输入地址"];
        return  NO;
    }
    
    if (![self isPureNumandCharacters:phoneTextView.text])
    {
        [self noticeError:@"您输入的电话必须为数字且为11位"];
        return NO;
    }
    
    if(![self validateEmail:emailTextView.text])
    {
        [self noticeError:@"您输入的邮箱不合法"];
        return NO;
    }
    
    if (boardTextView.text.length == 0)
    {
        [self noticeError:@"请输入出国意向"];
        return  NO;
    }
    
    
    return YES;
}

-(void)noticeError:(NSString*)str
{
    MBProgressHUD*   huderror=[[MBProgressHUD alloc]init];
    huderror.mode=MBProgressHUDModeCustomView;
    huderror.labelText=str;
    huderror.labelFont=[UIFont systemFontOfSize:14];
    [self addSubview:huderror];
    [huderror show:YES];
    [huderror performSelector:@selector(hideHud:) withObject:huderror afterDelay:1];
    
}


@end
